<?php
/**
 * A simple description for this script
 *
 * PHP Version 5.2.0 or Upper version
 *
 * @package    Paylog
 * @author     Hidehito NOZAWA aka Suin <http://suin.asia>
 * @copyright  2010 Hidehito NOZAWA
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU GPL v2
 *
 */

class Paylog_Object_GroupHandler extends Paylog_Abstract_ObjectHandler
{
	protected $object  = 'Paylog_Object_Group';
	protected $table   = 'group';
	protected $primary = 'id';

	public function load($id)
	{
		$obj = parent::load($id);

		$tagHand = new Paylog_Object_TagHandler;
		$obj->tagObjs = $tagHand->loadByGroupId($id);

		return $obj;
	}

	public function loads()
	{
		$sql = "SELECT * FROM `%s`";
		$sql = sprintf($sql, $this->table);

		$rsrc = $this->_query($sql);

		$objs = array();
		$tagHand = new Paylog_Object_TagHandler;

		while ( $vars = $this->db->fetchArray($rsrc) )
		{
			$obj = $this->create();
			$obj->unsetNew();
			$obj->setVars($vars);
			$obj->tagObjs = $tagHand->loadByGroupId($vars[$this->primary]);
			$objs[] = $obj;
		}

		return $objs;
	}

	public function loadOrderByWeight()
	{
		$sql = "SELECT * FROM `%s` ORDER BY `weight`, `%s`";
		$sql = sprintf($sql, $this->table, $this->primary);

		$rsrc = $this->_query($sql);

		$objs = array();
		$tagHand = new Paylog_Object_TagHandler;

		while ( $vars = $this->db->fetchArray($rsrc) )
		{
			$obj = $this->create();
			$obj->unsetNew();
			$obj->setVars($vars);
			$obj->tagObjs = $tagHand->loadByGroupId($vars[$this->primary]);
			$objs[] = $obj;
		}

		return $objs;
	}

	public function count()
	{
		$sql = "SELECT COUNT(`id`) FROM %s";
		$sql = sprintf($sql, $this->table);

		$result = $this->_query($sql);
		list($count) = $this->db->fetchRow($result);

		return $count;
	}

	public function isIdExists($id)
	{
		$id = intval($id);

		$sql = "SELECT COUNT(`id`) FROM %s WHERE `id` = '%u'";
		$sql = sprintf($sql, $this->table, $id);

		$result = $this->_query($sql);
		list($count) = $this->db->fetchRow($result);

		return ( $count > 0 );
	}
}

?>
